package org.example.leetcode.interview.queue;

import org.example.util.IO;

import java.util.HashMap;
import java.util.Map;
import java.util.PriorityQueue;

public class LC0347 {

    public int[] topKFrequent(int[] nums, int k) {
        int[] answ = new int[k];
        // 统计各元素出现的频率
        Map<Integer, Integer> freq = new HashMap<>();
        for (int i : nums) {
            freq.put(i, freq.getOrDefault(i, 0) + 1);
        }

        // 正排序构建小顶堆
        PriorityQueue<Map.Entry<Integer, Integer>> queue = new PriorityQueue<>((o1, o2) -> o1.getValue() - o2.getValue());
        for (Map.Entry<Integer, Integer> entry : freq.entrySet()) {
            queue.offer(entry);
            if (queue.size() > k) {
                queue.poll();
            }
        }

        for (int i = k - 1; i >= 0; i--) {
            answ[i] = queue.poll().getKey();
        }

        return answ;
    }

    public static void main(String[] args) {
        LC0347 solu = new LC0347();
        solu.topKFrequent(IO.intArray("[1,1,1,2,2,3]"), 2);
    }
}
